vim.api.nvim_create_autocmd("FileType", { pattern = "json", command = "set filetype=jsonc" })
vim.api.nvim_create_autocmd("FileType", { pattern = "zsh", command = "set filetype=sh" })

local function script_path()
  local str = debug.getinfo(2, "S").source:sub(2)
  return str:match "(.*/)"
end

local cmd_path = script_path() .. "/bin/im-select" .. "-" .. vim.loop.os_uname().machine
local win_path = script_path() .. "\\bin\\im-select.exe"

if vim.loop.os_uname().sysname == "Darwin" then
  local function swift_to_en() vim.loop.spawn(cmd_path, { args = { "com.apple.keylayout.ABC" } }) end
  -- vim.api.nvim_create_autocmd("ModeChanged", { pattern = { "*:n" }, callback = function() swift_to_en() end })
  vim.api.nvim_create_autocmd(
    { "VimEnter", "FocusGained", "InsertLeave", "CmdlineLeave" },
    { callback = function() swift_to_en() end }
  )
end

if vim.loop.os_uname().sysname == "Linux" then
  if vim.fn.executable "ibus" == 1 then
    local function linux_swift_to_en() vim.loop.spawn("ibus", { args = { "engine", "xkb:us::eng" } }) end
    vim.api.nvim_create_autocmd("ModeChanged", { pattern = { "*:n" }, callback = function() linux_swift_to_en() end })
    vim.api.nvim_create_autocmd(
      { "VimEnter", "FocusGained", "InsertLeave", "CmdlineLeave" },
      { callback = function() linux_swift_to_en() end }
    )
  end
  if vim.fn.executable "fcitx5-remote" == 1 then
    local function linux_swift_to_en() vim.loop.spawn("fcitx5-remote", { args = { "-c" } }) end
    vim.api.nvim_create_autocmd("ModeChanged", { pattern = { "*:n" }, callback = function() linux_swift_to_en() end })
    vim.api.nvim_create_autocmd(
      { "VimEnter", "FocusGained", "InsertLeave", "CmdlineLeave" },
      { callback = function() linux_swift_to_en() end }
    )
  end
  if vim.fn.executable "fcitx-remote" == 1 then
    local function linux_swift_to_en() vim.loop.spawn("fcitx-remote", { args = { "-c" } }) end
    vim.api.nvim_create_autocmd("ModeChanged", { pattern = { "*:n" }, callback = function() linux_swift_to_en() end })
    vim.api.nvim_create_autocmd(
      { "VimEnter", "FocusGained", "InsertLeave", "CmdlineLeave" },
      { callback = function() linux_swift_to_en() end }
    )
  end
end

-- git-bash
if vim.loop.os_uname().sysname == "Windows_NT" then
  local function win_swift_to_en() vim.loop.spawn(win_path, { args = { "1033" } }) end
  vim.api.nvim_create_autocmd("ModeChanged", { pattern = { "*:n" }, callback = function() win_swift_to_en() end })
  vim.api.nvim_create_autocmd(
    { "VimEnter", "FocusGained", "InsertLeave", "CmdlineLeave" },
    { callback = function() win_swift_to_en() end }
  )
end
